import React from 'react'
import { useHistory } from 'react-router-dom';
import { reqLogin } from '../../api';
import { saveUserNickname } from '../../util';
import './index.less';
import { Form, Input, Button, Checkbox, Card, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';



const Login = () => {

    const history = useHistory()

    function loginSuccess(result) {
        message.success(`登陆成功，欢迎你：${result.nickname}`)
        saveUserNickname(result)
        history.replace('/admin')
    }

    const onFinish = async (values) => {
        const { success, result } = await reqLogin(values)
        result.remember = values.remember;
        if (success) {
            loginSuccess(result)
        }
    };

    return (
        <div className="login-box">
            <Card className="login-center"
                size="small"
                title="管理员登陆"
                extra={<a href="#">More</a>}>
                <Form
                    name="normal_login"
                    className="login-form"
                    initialValues={{
                        remember: true,
                    }}
                    onFinish={onFinish}
                >
                    <Form.Item
                        name="nickname"
                        rules={[
                            {
                                required: true,
                                message: '请输入昵称或邮箱',
                            },
                        ]}
                    >
                        <Input prefix={<UserOutlined className="site-form-item-icon" />}
                            placeholder="昵称或邮箱" />
                    </Form.Item>
                    <Form.Item
                        name="password"
                        rules={[
                            {
                                required: true,
                                message: '请输入密码',
                            },
                        ]}
                    >
                        <Input
                            prefix={<LockOutlined className="site-form-item-icon" />}
                            type="password"
                            autoComplete="current-password"
                            placeholder="密码"
                        />
                    </Form.Item>
                    <Form.Item>
                        <Form.Item name="remember" valuePropName="checked" noStyle>
                            <Checkbox>记住我</Checkbox>
                        </Form.Item>
                    </Form.Item>

                    <Form.Item>
                        <Button type="primary" htmlType="submit" className="login-form-button">
                            登陆
                        </Button>
                    </Form.Item>
                </Form>
            </Card>
        </div>
    )
}

export default Login
